﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

namespace Treasland.MassiveGridMap.Editor {

    public enum enCanvasState {
        None,
        ReadyDrag,
    }

    public class MGridMapWindow : EditorWindow {

        /// <summary>
        /// 背景的坐标
        /// </summary>
        private float bgPanX = 0;
        private float bgPanY = 0;

        /// <summary>
        /// Canvas 最大拖动范围，-limitedPan limitedPan
        /// </summary>
        private float limitedPanX = 500;
        private float limitedPanY = 500;

        /// <summary>
        /// 放大缩小值
        /// </summary>
        private float zoomValue = 1f;

        /// <summary>
        /// 背景 Rect
        /// </summary>
        private Rect backgroundRect {
            get {
                return new Rect(0,0, position.width, position.height);
            }
        }

        /// <summary>
        /// 背景图片平铺 Rect
        /// </summary>
        private Rect backgroundUVRect {
            get {
                float x = (bgPanX % backgroundImg.width) / backgroundImg.width * -1;
                float y =  (bgPanY % backgroundImg.height) / backgroundImg.height;
                return new Rect(x ,y , position.width / backgroundImg.width * zoomValue, position.height / backgroundImg.height * zoomValue);
            }
        }

        /// <summary>
        /// 窗口背景图片
        /// </summary>
        private Texture2D backgroundImg;

        /// <summary>
        /// Canvas 状态
        /// </summary>
        private enCanvasState canvasState = enCanvasState.None;
        /// <summary>
        /// Canvas Rect
        /// </summary>
        private Rect canvasRect;

        /// <summary>
        /// 本编辑器的父路径
        /// </summary>
        private static string editorRootPath;


        private MapNode map = null;
        

        [MenuItem("Treasland/Map Editor")]
        private static void OpenWindow() {
            FindEditorRootPath();
            MGridMapWindow window = GetWindow<MGridMapWindow>();
            EditorUtility.LoadWindowLayout(editorRootPath + "Resources/Layout/MassiveGridMapEditorLayout.wlt");
            window.titleContent = new GUIContent("Map Editor");
            window.minSize = new Vector2(800, 700);
        }

        /// <summary>
        /// 查找编辑器的主目录
        /// </summary>
        private static void FindEditorRootPath() {
            string[] dirs = Directory.GetDirectories("Assets","*.*",SearchOption.AllDirectories);
            for(int i = 0; i < dirs.Length; ++i) {
                if (dirs[i].EndsWith("MassiveGridMap")) {
                    editorRootPath = dirs[i] + "/";
                    break;
                }
            }
        }

        private void OnEnable() {
            GUIStyleUtil.InitGUIStyles();
            backgroundImg = AssetDatabase.LoadAssetAtPath(editorRootPath + "Resources/Textures/background.png", typeof(Texture2D)) as Texture2D;
            canvasRect = new Rect(0, 0, position.width, position.height);
        }

        private void OnDisable() {
            
        }

        private void OnDestroy() {
            
        }

        /// <summary>
        /// 绘制背景
        /// </summary>
        private void DrawBackground() {
            GUI.DrawTextureWithTexCoords(backgroundRect, backgroundImg, backgroundUVRect);
        }

        private void OnGUI() {
            DrawBackground();
            DrawMap();

            ProcessMapEvent(Event.current);
            ProcessEvents(Event.current);

            Repaint();
        }

        /// <summary>
        /// 创立窗口相关的事件
        /// </summary>
        /// <param name="e"></param>
        private void ProcessEvents(Event e) {
            ProcessCanvasEvent(e); 
        }

       
        #region About Current Window
        /// <summary>
        /// 处理Canvas的事件，拖动，放大缩小
        /// </summary>
        /// <param name="e"></param>
        private void ProcessCanvasEvent(Event e) {
            if(e.type == EventType.MouseDown) {
                if(e.button == 2) {
                    canvasState = enCanvasState.ReadyDrag;
                }
            }

            if(e.type == EventType.MouseUp) {
                if(e.button == 2) {
                    canvasState = enCanvasState.None;
                }
            }

            if(e.type == EventType.MouseDrag && canvasState == enCanvasState.ReadyDrag) {

                if (map != null) {
                    //map.Drag(e.delta * zoomValue);
                    map.ForceDrag(e.delta * zoomValue);
                }

                bgPanX += e.delta.x * zoomValue;
                bgPanY += e.delta.y * zoomValue;

                GUI.changed = true;
            }

            // 滚轮放大功能
            //if (e.type == EventType.ScrollWheel) {
            //    float deltaY = e.delta.y;
            //    deltaY = Mathf.Clamp(deltaY, -1, 1);
            //    float zommSpeed = 0.05f;
            //    zoomValue += zommSpeed * deltaY;
            //    zoomValue = Mathf.Clamp(zoomValue, 0.6f, 1.0f);
            //    GUI.changed = true;
            //}
        }

        #endregion



        #region About Map
        private void DrawMap() {
            if (map == null) {
                return;
            }

            BeginWindows();
            map.Draw();
            EndWindows();
            GUI.changed = true;
        }


        private void ProcessMapEvent(Event e) {
            if (map == null) {
                if (e.type == EventType.MouseDown && e.button == 1) {
                    DrawCreateMapMenu(e.mousePosition);
                }
                return;
            }

            map.ProcessEvent(e);
        }


        private void DrawCreateMapMenu(Vector2 _mousePosition) {
            GenericMenu genericMenu = new GenericMenu();
            genericMenu.AddItem(new GUIContent("Create New Map"),
                                false,
                                () => OnClickCreateNewMap(_mousePosition));
            genericMenu.ShowAsContext();
                                
        }

        private void OnClickCreateNewMap(Vector2 _mousePosition) {
            MapNode mapNode = new MapNode(_mousePosition,
                                          200,
                                          100,
                                          GUIStyleUtil.mapNodeStyle,
                                          GUIStyleUtil.selectedMapNodeStyle,
                                          OnClickDeleteMap);
            map = mapNode;
        }
        

        private void OnClickDeleteMap(MapNode _mapNode) {
            Debug.Log("Delete Map Node");
        }

        #endregion


        #region About Node

        #endregion
    }
}
